<template>
  <div v-loading="loading" style="height: 100%">
    <van-nav-bar
        :right-text="postingDate"
        left-arrow
        left-text="返回"
        title="吨槽回收信息"
        @click-left="goBack"
        @click-right="setPostDate"
    />
    <van-calendar v-model="showCalendar" :max-date="maxDate" :min-date="minDate" @confirm="onConfirm"/>
    <van-cell-group
        :v-model="tableData"
        style="overflow: scroll; height: 520px"
    >
      <van-field
          ref="code_input"
          v-model="code_input"
          left-icon="scan"
          placeholder="请扫描条码"
          @input="onSubmitScanResult"
      />
      <van-divider
          content-position="left"
          style="height: 2px; font-style: italic"
      >信息
      </van-divider
      >
      <van-row style="border: solid 1px #3793fb; border-radius: 5px">
        <van-col span="24">
          <el-autocomplete id="autocompletePlant"
                           v-model="tableData.plant"
                           :fetch-suggestions="plantSearchPart"
                           :rules="{
                      required: true,
                      message: '请选择工厂',
                      trigger: 'blur',}"
                           label="接收工厂"
                           placeholder="工厂"
                           style="width: 100%;" value-key="plantname"
                           @input="plantStatus"></el-autocomplete>
        </van-col>
      </van-row>
      <van-row style="border: solid 1px #3793fb; border-radius: 5px">
        <van-col span="24">
          <el-autocomplete id="autocompleteSupplier" v-model="tableData.zzcys" :fetch-suggestions="supplierSearch"
                           :rules="{
                      required: true,
                      message: '请选择运输公司',
                      trigger: 'blur',
                    }" label="运输公司" placeholder="运输公司" style="width: 100%;"
                           value-key="codeanddes"></el-autocomplete>
        </van-col>
      </van-row>
      <van-button @click="queryCarNoLists"
                  style="
                    border: #3793fb solid 1px;
                    border-radius: 2px;
                    background-color: #3793fb;
                    line-height: var(--footer-height);
                  "
                  type="primary" block>查询车牌号清单</van-button>
      <van-field
          :value="tableData.carNo"
          label="车牌号"
          style="border: solid 1px #3793fb; border-radius: 5px"
          @click="show = true"
      />
      <vnp-keyboard v-model="tableData.carNo"
                    :show.sync="show" @input="carNoStatus"></vnp-keyboard>
      <van-row style="border: solid 1px #3793fb; border-radius: 5px">
        <van-col span="24">
          <el-autocomplete id="autocompletePart" v-model="tableData.location"
                           :fetch-suggestions="storageLocationSearchPart"
                           :rules="{
                      required: true,
                      message: '请选择库位',
                      trigger: 'blur',
                    }" label="库位" placeholder="库位" style="width: 100%;"
                           value-key="codeanddes"></el-autocomplete>
        </van-col>
      </van-row>
      <van-collapse v-model="activeName">
        <van-collapse-item v-for="(item, index) in tableData.details" :key="index" :name="index">
          <template #title> 客户 {{ item.customername }}</template>
          <van-field v-model="item.quantity" label="桶数：" readonly/>
        </van-collapse-item>
      </van-collapse>
      <van-swipe ref="swiper" style="border: solid #3793fb 1px;border-top:none" width="100%" @change="onChange">
        <van-swipe-item v-for="(item, index) in tableData.recycledata" :key="index" :name="index">
          <van-field v-model="item.numberofbarrels" label="桶号" readonly></van-field>
          <van-field v-model="item.customername" label="客户名称：" readonly/>
          <van-field v-model="item.commodityname" label="商品名称：" readonly/>
          <van-field v-model="item.allovers" label="余重：" @input="quantityChange(index)"/>
          <van-field v-model="item.brgew" label="桶重：" readonly/>
          <van-field v-model="item.leftovers" label="余料：" readonly/>
          <van-field v-model="item.sapmsg" label="PDA提醒：" readonly/>
          <van-button v-if="current >= 0" class="custom-swipe-delete"
                      color="linear-gradient(to right, #ff6034, #ee0a24)"
                      @click="onDeleteBarrel(index)">
            删除
          </van-button>
        </van-swipe-item>
        <template #indicator>
          <div v-if="current >= 0" class="custom-indicator">
            {{ current + 1 }}/{{ totalSize }}
          </div>
        </template>
      </van-swipe>
      <!--      <van-collapse v-model="activeNames">-->
      <!--        <van-collapse-item v-for="(item, index) in tableData.recycledata" :key="index" :name="index">-->
      <!--          <template #title> 桶信息 {{ item.numberofbarrels }}</template>-->
      <!--          <van-field v-model="item.numberofbarrels" label="桶号：" readonly/>-->
      <!--          <van-field v-model="item.customername" label="客户名称：" readonly/>-->
      <!--          <van-field v-model="item.commodityname" label="商品名称：" readonly/>-->
      <!--          <van-field v-model="item.allovers" label="余重：" @input="quantityChange(index)"/>-->
      <!--          <van-field v-model="item.brgew" label="桶重：" readonly/>-->
      <!--          <van-field v-model="item.leftovers" label="余料：" readonly/>-->
      <!--        </van-collapse-item>-->
      <!--      </van-collapse>-->
    </van-cell-group>
    <van-button
        block
        style="
        position: fixed;
        bottom: 0px;
        border: #3793fb solid 1px;
        border-radius: 2px;
        background-color: #3793fb;
        line-height: var(--footer-height);
      "
        type="primary"
        @click="onSubmit"
    >吨槽回收
    </van-button>
  </div>
</template>

<script>
import Keyboard from "../../assets/views/vnp-keyboard.vue";

export default {
  components: {'vnp-keyboard': Keyboard,},
  data() {
    return {
      activeName: ['1'], // 默认展开第一项
      activeNames: ['1'], // 默认展开第一项
      plantList: [],
      items: [],
      minDate: this.getMonthBeforeDate(),
      maxDate: this.getMonthAfterDate(),
      tableData: {
        carNo: '',
        zzcys: '',
        recycledata: [],
        details: [],
        plant: '',
        location: '',
      },
      loading: false,
      showCalendar: false,
      postingDate: this.getNowFormatDate(new Date()),
      storageLocationList: [],
      supplierList: [],
      index: 0,
      totalSize: 0,
      current: -1,
      quantity: '',
      code_input: '',
      isReturn: false,
      show: false
    };
  },
  mounted() {
    //车牌赋值
    this.returnCarNo(this.$route.query.isReturn,this.$route.query.tableData,this.$route.query.codeInfo);
    //获取库位List
    this.getStorageLocationList();
    //获取供应商List
    this.getSupplierList();
    //获取工厂
    this.getPlantList();
  },
  methods: {
    quantityChange(i) {
      console.log("$event", i)
      this.tableData.recycledata[i].leftovers = parseInt(this.tableData.recycledata[i].allovers) - parseInt(this.tableData.recycledata[i].brgew);
    },
    onSubmitScanResult(event) {
      this.getBucket(event);
    },
    async getBucket(bucketNo) {
      let scanInfo = {
        code: bucketNo,
      };
      const {data: res} = await this.$http.post(
          "/RecycleToneSlotsList",
          scanInfo
      );
      console.log("res", res);
      if (res.length && res[0].numberofbarrels) {
        var requestData = this.tableData;
        for (var i in requestData.recycledata) {
          if (requestData.recycledata[i].numberofbarrels === res[0].numberofbarrels) {
            this.$message({
              message: "扫描失败，请勿重复扫描同一桶号",
              type: "error",
            });
            this.code_input = '';
            return
          }
        }
        if ('交货' !== res[0].bucketstatus) {
          this.$toast.fail('条码信息错误,非交货状态');
          this.code_input = '';
          return
        }
        this.code_input = '';
        this.tableData.recycledata.push(res[0]);
        this.tableData.plant = localStorage.getItem("plant");
        this.totalSize = this.tableData.recycledata.length;
        this.current = this.totalSize - 1;
        this.$refs.swiper.swipeTo(this.current);
        this.tableData.zzcys = '0000001030';
        if ('6000' === this.tableData.plant) {
          this.tableData.location = '0219';
        }
        if ('6010' === this.tableData.plant) {
          this.tableData.location = 'X007';
        }
        var newQuantity = 1;
        for (let i in requestData.details) {
          if (requestData.details[i].customername === res[0].customername) {
            requestData.details[i].quantity = Number(requestData.details[i].quantity) + 1;
            return
          }
        }
        this.tableData.details.push({customername: res[0].customername, quantity: newQuantity});
      } else {
        this.code_input = '';
        this.$toast.fail('条码信息错误');
      }
    },
    //坉槽翻页
    onChange(index) {
      this.current = index;
    },
    onDeleteBarrel(index) {
      this.tableData.recycledata.splice(index, 1);
      this.tableData.noofbarrels -= 1;
      this.totalSize = this.tableData.recycledata.length;
      if (this.current > this.totalSize - 1) {
        this.current = this.totalSize - 1;
      }
      this.$refs.swiper.swipeTo(this.current);
    },
    //工厂搜索帮助
    plantSearchPart(queryString, cb) {
      var plantList = this.plantList;
      var results = queryString
          ? plantList.filter(this.plantFilter(queryString))
          : plantList;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    plantStatus() {
      let plantSplit = this.tableData.plant.split("|")[0];
      if ('6000' === plantSplit) {
        this.tableData.location = '0219';
      }
      if ('6010' === plantSplit) {
        this.tableData.location = 'X007';
      }
    },
    plantFilter(queryString) {
      return (storageLocation) => {
        return (
            storageLocation.plantname
                .toLowerCase()
                .indexOf(queryString.toLowerCase()) !== -1
        );
      };
    },
    carNoStatus() {
      this.getcarNo();
    },
    async getcarNo() {
      let scanInfo = {
        plant: this.tableData.zzcys,
        carNo: this.tableData.carNo,
      };
      const {data: Status} = await this.$http.post(
          "/CarNoList",
          scanInfo
      );
      var response = Status[0];
      console.log(response);
      if (response.type == "E") {
        this.$message({
          message: response.message,
          type: "error",
        });
        this.tableData.carNo = '';
      }
    },

    setPostDate() {
      this.showCalendar = true;
    },
    onConfirm(date) {
      this.showCalendar = false;
      this.$dialog.confirm({
        title: '过账日期',
        message: '此选择将更改ERP过账日期',
      })
          .then(() => {
            this.postingDate = this.getNowFormatDate(date);
          })
          .catch(() => {
          });
    },
    async getPlantList() {
      let scanInfo = {};
      const {data: res} = await this.$http.post(
          "/PlantList",
          scanInfo
      );
      this.plantList = res;
    },

    async getSupplierList() {
      let scanInfo = {
        plant: localStorage.getItem("plant"),
      };
      const {data: res} = await this.$http.post(
          "/SupplierList",
          scanInfo
      );
      this.supplierList = res;
    },
    //库位搜索帮助
    supplierSearch(queryString, cb) {
      var supplierList = this.supplierList;
      var results = queryString
          ? supplierList.filter(this.createFilter(queryString))
          : supplierList;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },

    async getStorageLocationList() {
      let scanInfo = {
        plant: localStorage.getItem("plant"),
      };
      const {data: res} = await this.$http.post(
          "/StorageLocationList",
          scanInfo
      );
      this.storageLocationList = res;
    },
    //库位搜索帮助
    storageLocationSearchPart(queryString, cb) {
      var storageLocationList = this.storageLocationList;
      var results = queryString
          ? storageLocationList.filter(this.createFilter(queryString))
          : storageLocationList;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (storageLocation) => {
        return (
            storageLocation.codeanddes
                .toLowerCase()
                .indexOf(queryString.toLowerCase()) !== -1
        );
      };
    },
    //返回
    goBack() {
      this.$router.push("/HomePage");
    },
    //吨槽回收
    onSubmit() {
      this.loading = true;
      setTimeout(() => {
        this.loading = false;
        this.postRecycleToneSlots();
      }, 1000);
      this.dialogVisible = false;
    },
    //过账接口
    async postRecycleToneSlots() {
      var requestData = this.tableData;
      console.log("requestData", requestData);
      let inputInfo = {
        plant: localStorage.getItem("plant"),
        persnumber: localStorage.getItem("erpId"),
        postdate: this.postingDate,
        zzcys: requestData.zzcys.split("|")[0],
        zzcysDes: requestData.zzcys.split("|")[1],
        carNo: requestData.carNo,
        location: requestData.location.split("|")[0],
        recycledata: requestData.recycledata,
      };
      console.log("inputInfo", inputInfo)
      const {data: res} = await this.$http.post(
          "/RecycleToneSlotsPost",
          inputInfo
      );
      var response = res[0];
      console.log("response", response)
      if (response.type == "S") {
        this.$toast.success(response.message);
        setTimeout(() => {
          this.$router.push("/HomePage");
        }, 1000);
      } else if (response.type == "E") {
        this.$message({
          message: response.message,
          type: "error",
        });
      } else {
        this.$message({
          message: "入库失败，请联系系统维护人员",
          type: "error",
        });
      }
    },
    queryCarNoLists(){
      if(!this.tableData.zzcys){
        this.$message({
          message: "请先选择运输公司",
          type: "error",
        });
        return
      }
      this.$router.push({
        path: "/CarNoListInfo",
        query: { tableData : this.tableData },
      });
    },
    returnCarNo(isReturn,tableData,codeInfo){
      this.isReturn = isReturn;
      if(this.isReturn){
        setTimeout(() => {
          this.tableData = tableData;
          this.tableData.carNo = codeInfo;
          this.getcarNo();
        }, 0);
      }
    },
  },
};
</script>
<style></style>
